package collections.concurrenthashmap;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述：组合操作并不保证线程安全，需要while循环 + replace才可以保证线程安全
 */

public class OptionsNotSafe implements Runnable {
    private static ConcurrentHashMap<String, Integer> scoreMap = new ConcurrentHashMap<>();
    public static void main(String[] args) throws InterruptedException {
        scoreMap.put("a", 0);
        Thread t1 = new Thread(new OptionsNotSafe());
        t1.start();
        Thread t2 = new Thread(new OptionsNotSafe());
        t2.start();
        t1.join();
        t2.join();
        System.out.println(scoreMap.get("a")); // 等于2000
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            while (true) {
                Integer score = scoreMap.get("a");
                Integer newScore = score + 1;
                boolean b = scoreMap.replace("a", score, newScore);
                if (b) {
                    break;
                }
            }
        }
    }
}
